"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { motion } from "framer-motion"
import { 
  Search, 
  Filter, 
  Users, 
  MapPin, 
  Calendar,
  Plus,
  Star,
  Trophy,
  ChevronRight
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useAuth } from "@/contexts/auth-context"
import { LoadingScreen } from "@/components/loading-screen"

interface Team {
  id: string
  name: string
  description: string
  avatar_url?: string
  member_count: number
  max_members: number
  skills: string[]
  location?: string
  created_at: string
  is_recruiting: boolean
  competition_id?: string
  competition_name?: string
  leader: {
    id: string
    username: string
    avatar_url?: string
  }
}

export default function TeamsPage() {
  const router = useRouter()
  const { isAuthenticated } = useAuth()
  const [teams, setTeams] = useState<Team[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState("")
  const [filterStatus, setFilterStatus] = useState("all")
  const [filterSkill, setFilterSkill] = useState("all")

  useEffect(() => {
    const fetchTeams = async () => {
      try {
        setIsLoading(true)
        // TODO: 实现团队API调用
        // const response = await teamsApi.getTeams()
        // setTeams(response.data)
        
        // 模拟数据
        const mockTeams: Team[] = [
          {
            id: "1",
            name: "CodeCrafters",
            description: "专注于Web开发和AI应用的团队，寻找有经验的前端和后端开发者",
            avatar_url: "",
            member_count: 3,
            max_members: 5,
            skills: ["React", "Node.js", "Python", "AI"],
            location: "北京",
            created_at: "2024-01-15T00:00:00Z",
            is_recruiting: true,
            competition_id: "1",
            competition_name: "2024 AI创新大赛",
            leader: {
              id: "1",
              username: "techleader",
              avatar_url: ""
            }
          },
          {
            id: "2",
            name: "DataMiners",
            description: "数据科学和机器学习专家团队，致力于解决复杂的数据问题",
            avatar_url: "",
            member_count: 4,
            max_members: 6,
            skills: ["Python", "TensorFlow", "SQL", "Statistics"],
            location: "上海",
            created_at: "2024-01-10T00:00:00Z",
            is_recruiting: true,
            leader: {
              id: "2",
              username: "datascientist",
              avatar_url: ""
            }
          },
          {
            id: "3",
            name: "MobileFirst",
            description: "移动应用开发团队，专注于iOS和Android平台",
            avatar_url: "",
            member_count: 5,
            max_members: 5,
            skills: ["Swift", "Kotlin", "React Native", "Flutter"],
            location: "深圳",
            created_at: "2024-01-05T00:00:00Z",
            is_recruiting: false,
            competition_id: "2",
            competition_name: "移动应用创新挑战赛",
            leader: {
              id: "3",
              username: "mobiledev",
              avatar_url: ""
            }
          }
        ]
        setTeams(mockTeams)
      } catch (error) {
        console.error("Failed to fetch teams:", error)
      } finally {
        setIsLoading(false)
      }
    }

    fetchTeams()
  }, [])

  const filteredTeams = teams.filter(team => {
    const matchesSearch = team.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         team.description.toLowerCase().includes(searchQuery.toLowerCase())
    
    const matchesStatus = filterStatus === "all" || 
                         (filterStatus === "recruiting" && team.is_recruiting) ||
                         (filterStatus === "full" && !team.is_recruiting)
    
    const matchesSkill = filterSkill === "all" || 
                        team.skills.some(skill => skill.toLowerCase().includes(filterSkill.toLowerCase()))
    
    return matchesSearch && matchesStatus && matchesSkill
  })

  const handleCreateTeam = () => {
    router.push("/teams/create")
  }

  const handleJoinTeam = (teamId: string) => {
    // TODO: 实现加入团队的逻辑
    console.log("Join team:", teamId)
  }

  if (isLoading) {
    return <LoadingScreen />
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 页面标题和创建按钮 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex justify-between items-center mb-8"
        >
          <div>
            <h1 className="text-3xl font-bold text-white mb-2">团队广场</h1>
            <p className="text-gray-300">找到志同道合的队友，一起参加竞赛</p>
          </div>
          <Button
            onClick={handleCreateTeam}
            className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
          >
            <Plus className="w-4 h-4 mr-2" />
            创建团队
          </Button>
        </motion.div>

        {/* 搜索和筛选 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="mb-8"
        >
          <Card className="bg-gray-800/50 border-gray-700">
            <CardContent className="p-6">
              <div className="flex flex-col md:flex-row gap-4">
                <div className="flex-1 relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <Input
                    placeholder="搜索团队名称或描述..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-10 bg-gray-700 border-gray-600 text-white"
                  />
                </div>
                <Select value={filterStatus} onValueChange={setFilterStatus}>
                  <SelectTrigger className="w-full md:w-48 bg-gray-700 border-gray-600 text-white">
                    <SelectValue placeholder="招募状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="recruiting">正在招募</SelectItem>
                    <SelectItem value="full">已满员</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={filterSkill} onValueChange={setFilterSkill}>
                  <SelectTrigger className="w-full md:w-48 bg-gray-700 border-gray-600 text-white">
                    <SelectValue placeholder="技能筛选" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部技能</SelectItem>
                    <SelectItem value="react">React</SelectItem>
                    <SelectItem value="python">Python</SelectItem>
                    <SelectItem value="node">Node.js</SelectItem>
                    <SelectItem value="ai">AI/ML</SelectItem>
                    <SelectItem value="mobile">移动开发</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* 团队列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
        >
          {filteredTeams.map((team, index) => (
            <motion.div
              key={team.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 * index }}
            >
              <Card className="bg-gray-800/50 border-gray-700 hover:border-blue-500/50 transition-all duration-300 cursor-pointer group">
                <CardHeader className="pb-4">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <Avatar className="w-12 h-12">
                        <AvatarImage src={team.avatar_url || ""} alt={team.name} />
                        <AvatarFallback className="bg-gradient-to-r from-blue-500 to-purple-500">
                          {team.name.charAt(0).toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <CardTitle className="text-white text-lg group-hover:text-blue-300 transition-colors">
                          {team.name}
                        </CardTitle>
                        <div className="flex items-center gap-2 mt-1">
                          <Badge 
                            variant={team.is_recruiting ? "default" : "secondary"}
                            className={team.is_recruiting ? "bg-green-500/20 text-green-300" : "bg-gray-500/20 text-gray-300"}
                          >
                            {team.is_recruiting ? "招募中" : "已满员"}
                          </Badge>
                        </div>
                      </div>
                    </div>
                    <ChevronRight className="w-5 h-5 text-gray-400 group-hover:text-blue-300 transition-colors" />
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  <p className="text-gray-300 text-sm line-clamp-3">{team.description}</p>
                  
                  {/* 团队信息 */}
                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-sm text-gray-400">
                      <Users className="w-4 h-4" />
                      <span>{team.member_count}/{team.max_members} 成员</span>
                    </div>
                    {team.location && (
                      <div className="flex items-center gap-2 text-sm text-gray-400">
                        <MapPin className="w-4 h-4" />
                        <span>{team.location}</span>
                      </div>
                    )}
                    <div className="flex items-center gap-2 text-sm text-gray-400">
                      <Calendar className="w-4 h-4" />
                      <span>创建于 {new Date(team.created_at).toLocaleDateString("zh-CN")}</span>
                    </div>
                    {team.competition_name && (
                      <div className="flex items-center gap-2 text-sm text-gray-400">
                        <Trophy className="w-4 h-4" />
                        <span>{team.competition_name}</span>
                      </div>
                    )}
                  </div>

                  {/* 技能标签 */}
                  <div className="flex flex-wrap gap-1">
                    {team.skills.slice(0, 4).map((skill) => (
                      <Badge key={skill} variant="outline" className="text-xs border-gray-600 text-gray-300">
                        {skill}
                      </Badge>
                    ))}
                    {team.skills.length > 4 && (
                      <Badge variant="outline" className="text-xs border-gray-600 text-gray-300">
                        +{team.skills.length - 4}
                      </Badge>
                    )}
                  </div>

                  {/* 队长信息 */}
                  <div className="flex items-center gap-2 pt-2 border-t border-gray-700">
                    <Avatar className="w-6 h-6">
                      <AvatarImage src={team.leader.avatar_url || ""} alt={team.leader.username} />
                      <AvatarFallback className="text-xs bg-gray-600">
                        {team.leader.username.charAt(0).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <span className="text-sm text-gray-400">队长: {team.leader.username}</span>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex gap-2 pt-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1 border-gray-600 text-white hover:bg-gray-700"
                      onClick={(e) => {
                        e.stopPropagation()
                        router.push(`/teams/${team.id}`)
                      }}
                    >
                      查看详情
                    </Button>
                    {team.is_recruiting && (
                      <Button
                        size="sm"
                        className="flex-1 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                        onClick={(e) => {
                          e.stopPropagation()
                          handleJoinTeam(team.id)
                        }}
                      >
                        申请加入
                      </Button>
                    )}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          ))}
        </motion.div>

        {/* 空状态 */}
        {filteredTeams.length === 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="text-center py-12"
          >
            <div className="text-6xl mb-4">👥</div>
            <h3 className="text-xl font-semibold text-white mb-2">没有找到团队</h3>
            <p className="text-gray-300 mb-6">
              {searchQuery || filterStatus !== "all" || filterSkill !== "all" 
                ? "尝试调整搜索条件或筛选器" 
                : "还没有团队，成为第一个创建团队的人吧！"
              }
            </p>
            <Button
              onClick={handleCreateTeam}
              className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
            >
              <Plus className="w-4 h-4 mr-2" />
              创建团队
            </Button>
          </motion.div>
        )}
      </div>
    </div>
  )
}